/*
 * @Author: 徐建辰
 * @Date: 2022-02-15 09:37:59
 * @LastEditTime: 2022-02-15 15:01:05
 * @LastEditors: 徐建辰
 * @Description: 使用hook抽离地址模块代码
 */
import {ref, onMounted} from 'vue'
import {Toast, Dialog} from 'vant'
import {antiShake} from '@/utils/utils'
import {addAddress, editAddress, deleteAddress, getAddressDetail, getDefaultAddress} from '@/service/address'
import {areaCode} from '@/plugins/mock'
 
export default function useAddress(route, router, getDefault = false) {
  const types = ref('add')
  const addrId = ref('')
  const searchResult = ref([])
  const addressInfo = ref({})
  const defaultAddress = ref({})
  const arealist = ref({
    province_list: {},
    city_list: {},
    county_list: {}
  })

  onMounted(async () => {
    !getDefault && genarateAreaData()
    getDefault && getDefaultAddr()
  })

  // 保存
  function onSave(content) {
    console.log(router)
    Toast.loading('保存中...')
    antiShake(async () => {
      const typeVal = types.value
      const params = {
        userName: content.name,
        userPhone: content.tel,
        provinceName: content.province,
        cityName: content.city,
        regionName: content.county,
        detailAddress: content.addressDetail,
        defaultFlag: content.isDefault ? 1 : 0,
      }
      if (typeVal === 'edit') {
        params['addressId'] = addrId.value
      }
      await typeVal === 'add' ? addAddress(params) : editAddress(params)
      Toast('保存成功')
      setTimeout(() => router.back(), 1000)
    })
  }
  // 删除
  function onDelete(id) {
    Dialog.alert({
      title: '温馨提示！',
      message: '确定要删除此地址吗？',
    }).then(async () => {
      const {resultCode} = await deleteAddress(id)
      if (resultCode !== 200) return
      Toast.success('删除成功')
      setTimeout(() => router.back(), 1000)
    })
  }
  // 填充数据
  async function genarateAreaData() {
    // 省市区列表构造
    let _province_list = {}
    let _city_list = {}
    let _county_list = {}
    areaCode.getLev1().forEach(p => {
      _province_list[p.id] = p.text
      areaCode.getLev2(p.id).forEach(c => {
        _city_list[c.id] = c.text
        areaCode.getLev3(c.id).forEach(q => _county_list[q.id] = q.text)
      })
    })
    arealist.value.province_list = _province_list
    arealist.value.city_list = _city_list
    arealist.value.county_list = _county_list

    const {addressId = '', type, from} = route.query
    addrId.value = addressId
    types.value = type
    if (type === 'edit') {
      const {data: addressDetail} = await getAddressDetail(addressId)
      let _areaCode = ''
      const province = areaCode.getLev1()
      Object.entries(arealist.value.county_list).forEach(([id, text]) => {
        // 先找出当前对应的区
        if (text === addressDetail.regionName) {
          // 找到区对应的几个省份
          const provinceIndex = province.findIndex(item => item.id.substr(0, 2) == id.substr(0, 2))
          // 找到区对应的几个市区
          // eslint-disable-next-line no-unused-vars
          const cityItem = Object.entries(arealist.value.city_list).filter(([cityId, cityName]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
          // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
          if (province[provinceIndex].text == addressDetail.provinceName && cityItem[1] == addressDetail.cityName) {
            _areaCode = id
          }
        }
      })

      addressInfo.value = {
        id: addressDetail.addressId,
        name: addressDetail.userName,
        tel: addressDetail.userPhone,
        province: addressDetail.provinceName,
        city: addressDetail.cityName,
        county: addressDetail.regionName,
        addressDetail: addressDetail.detailAddress,
        areaCode: _areaCode,
        isDefault: !!addressDetail.defaultFlag
      }
    }
  }
  // 获取默认地址
  async function getDefaultAddr() {
    const {data, resultCode} = await getDefaultAddress()
    if (resultCode !== 200 || !data) {
      Toast('获取默认地址失败')
      return
    }
    defaultAddress.value = data
  }

  return {
    types, addrId, searchResult, addressInfo, arealist, defaultAddress,
    genarateAreaData, onSave, onDelete
  }
}